package com.evol.service;

import com.alibaba.fastjson.JSONObject;
import com.evol.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author EvOL
 * @description
 * @date 2024-06-02 14:03
 **/
@Service
public class JsonFileService {
    private final ResourceLoader resourceLoader;

    @Autowired
    public JsonFileService(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public String readJsonFileAsString(String filePath) {
        try{
            String currentDirectory = System.getProperty("user.dir");
            String fullPath = currentDirectory + File.separator +filePath;
            File externalFile = new File(fullPath);
            if (externalFile.exists()) {
                try (InputStream inputStream = new FileInputStream(externalFile)) {
                    return readFromInputStream(inputStream);
                }
            }

            Resource resource = resourceLoader.getResource("classpath:" + filePath);
            if (resource.exists()) {
                try (InputStream inputStream = resource.getInputStream()) {
                    return readFromInputStream(inputStream);
                }catch (Exception es){

                }
            } else {
                return null;
            }
        }catch (Exception es){}
        return null;
    }

    public JSONObject parseJsonString(String filePath) {
        String data=readJsonFileAsString(filePath);
        if(StringUtils.isNotEmpty(data)){
            return JSONObject.parseObject(data);
        }else{
            return null;
        }

    }
    public void saveJsonFile(String filePath, String jsonString) {
        String currentDirectory = System.getProperty("user.dir");
        String fullPath = currentDirectory + File.separator + filePath;
        File externalFile = new File( fullPath);
        try {
            // 创建父目录（如果不存在）
            File parentDir = externalFile.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                if (!parentDir.mkdirs()) {
                    throw new IOException("Failed to create directory: " + parentDir);
                }
            }
            // 写入文件
            try (FileWriter fileWriter = new FileWriter(externalFile)) {
                fileWriter.write(jsonString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private String readFromInputStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int nRead;
        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        inputStream.close();
        return new String(buffer.toByteArray(), StandardCharsets.UTF_8);
    }
}
